package utils;

import java.sql.*;

public class DBUtils {

    public static Connection getConnection() throws SQLException, ClassNotFoundException {
        String DRIVER = "com.mysql.cj.jdbc.Driver";
        String DBNAME ="root";
        String DBUSEPASS = "123456";
        String dbName = "db_dorm";
        String url1 = "jdbc:mysql://localhost:3306/"+dbName;
        String url2 = "?useSSL=false&serverTimezone=UTC";
        String url3 = "&userUnicode=true&characterEncoding=UTF-8";
        String URL = url1+url2+url3;

        Class.forName(DRIVER);
        Connection con = DriverManager.getConnection(URL,DBNAME,DBUSEPASS);
        return con;
    }

    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static int executeUpdate(String sql, Object... params) {
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);
            // 设置参数
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }
            return pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        } finally {
            close(conn, pstmt, null);
        }
    }

    public static ResultSet executeQuery(String sql, Object... params) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);
            // 设置参数
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }
            rs = pstmt.executeQuery();
            // 注意：这里不关闭连接，由调用者处理
            return rs;
        } catch (Exception e) {
            e.printStackTrace();
            close(conn, pstmt, rs);
            return null;
        }
    }

    public static void testConnection() {
        try (Connection conn = getConnection()) {
            System.out.println("数据库连接测试成功!");
        } catch (Exception e) {
            System.out.println("数据库连接测试失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        testConnection();
    }
}